/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.oss.cloud;

import com.qcloud.cos.internal.CosServiceRequest;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.qiniu.storage.BucketManager;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 七牛云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class QiniuCloudStorageService extends AbstractCloudStorageService {
    private UploadManager uploadManager;
    BucketManager bucketManager;
    private String token;

    public QiniuCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
        Auth auth = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey());
        bucketManager = new BucketManager(auth,new Configuration(Region.autoRegion()));
        token = auth.uploadToken(config.getQiniuBucketName());

    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, res.toString());
            }
        } catch (Exception e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        return config.getQiniuDomain() + "/" + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQiniuPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
    }

    @Override
    public void delete( String key) {
            String keys = getKey(config.getQiniuPrefix(),key);
        try {
            Response res = bucketManager.delete(config.getQiniuBucketName(), keys);
            if (!res.isOK()) {
                throw new RenException(ErrorCode.OSS_DELETE_FILE_ERROR, res.toString());
            }
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            System.err.println(ex.response.toString());
        }finally {

        }
    }

    @Override
    public void download(String key, String pathName) {
        String keys = getKey(config.getQiniuPrefix(),key);
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(keys, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String finalUrl = String.format("%s/%s",config.getQiniuDomain() , encodedFileName);

        //下载到本地
        try {
            URL httpurl = new URL(finalUrl);
            File dirfile = new File(pathName);
            if (!dirfile.exists()) {
                dirfile.mkdirs();
            }
            FileUtils.copyURLToFile(httpurl, new File(pathName+'/'+key));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
